package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理系统
 */
@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增套餐接口，同时需要保存套餐和菜品的关联关系
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R saveWithDish( @RequestBody SetmealDto setmealDto ) {
        //1、保存套餐数据到 setmeal表中 ： SetmealMapper
        setmealService.save(setmealDto);
        //2、保存套餐菜品数据到 setmeal_dish表中： SetmealDishMapper
        //2.1 获取当前套餐的菜品列表
        List<SetmealDish> dishes = setmealDto.getSetmealDishes();
        //2.2 循环遍历，获取每一个套餐菜品数据 setmealDish
        for (SetmealDish dish : dishes) {
            //2.3 获取套餐id，并set到setmealDish中
            dish.setSetmealId(setmealDto.getId());
        }
        //2.4 保存套餐菜品数据 setmealDish
        setmealDishService.saveBatch(dishes);
        return R.success(dishes);
    }

    /**
     * 套餐分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page( Integer page, Integer pageSize, String name ) {
        //分页器构造对象
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> dtoPage = new Page<>();
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        //添加查询条件
        qw.like(name != null, Setmeal::getName, name);
        //添加排序条件
        qw.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo, qw);
        //对象拷贝
        BeanUtil.copyProperties(pageInfo, dtoPage, "records");
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map(( item ) -> {
                    SetmealDto setmealDto = new SetmealDto();
                    //对象拷贝
                    BeanUtil.copyProperties(item, setmealDto);
                    //分类id
                    Long categoryId = item.getCategoryId();
                    //根据分类id查询对象
                    Category category = categoryService.getById(categoryId);
                    if (category != null) {
                        String categoryName = category.getName();
                        setmealDto.setCategoryName(categoryName);
                    }
                    return setmealDto;
                }
        ).collect(Collectors.toList());
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 删除套餐
     *
     * @param ids
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R removeWithDish( @RequestParam List<Long> ids ) {
        //查询套餐状态，确定是否可用删除
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.in(Setmeal::getId, ids);
        qw.eq(Setmeal::getStatus, 1);
        int count = setmealService.count(qw);
        if (count > 0) {
            //如果不能删除，给出提示
            return R.error("套餐正在售卖中，不能删除");
        } else {
            //如果可以删除，先删除套餐表中的数据---setmeal
            setmealService.removeByIds(ids);
        }
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.in(SetmealDish::getSetmealId, ids);
        //删除关系表中的数据----setmeal_dish
        setmealDishService.remove(lqw);
        return R.success("操作成功");
    }
     /*   //1、判断当前要删除的套餐是否处于售卖状态，如果是，不允许删除
        // select count(*) from setmeal where id in (1,2,3) and status = 1
        for (Long id : ids) {
            Setmeal setmeal = setmealService.getById(id);
            if (setmeal.getStatus()==0){
                R.error("套餐正在售卖中，不能删除");
            }
        }
        //2、删除套餐： delete from setmeal where id in (1,2,3)
                setmealService.removeByIds(ids);
        //3、删除套餐对应的菜品数据：delete from setmeal_dish where setmeal_id in (1,2,3)
        for (Long id : ids) {
            LambdaQueryWrapper<SetmealDish> qw =new LambdaQueryWrapper<>();
            qw.eq(SetmealDish::getSetmealId,id);
            setmealDishService.remove(qw);
        }
        return R.success("删除成功");
    }*/

    /**
     * 起售停售套餐
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R updateStatus( @PathVariable Integer status, @RequestParam List<Long> ids ) {
        for (Long id : ids) {
            Setmeal byId = setmealService.getById(id);
            byId.setStatus(status);
            setmealService.updateById(byId);
        }
        return R.success("删除成功");
    }

    /**
     * 根据套餐id查询套餐数据
     *
     * @param
     * @return
     */
    @GetMapping("/{id}")
    @CacheEvict(value = "setmealCache",key = "#id")
    public R<SetmealDto> getById( @PathVariable Long id ) {
        //1、根据套餐id查询套餐数据 select * from setmeal where id =?
        Setmeal setmeal = setmealService.getById(id);
        //2、根据套餐id查询套餐对应的菜品数据 select * from setmeal_dish where setmeal_id = ?
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(qw);
        //3、将套餐 setmeal 和套餐菜品集合 setmealDishList 数据封装到 SetmealDto并返回
        // 3.0 首先new一个SetmealDto对象
        SetmealDto setmealDto = new SetmealDto();
        // 3.1、BeanUtils.copyProperties() 拷贝setmeal到setmealDto中
        BeanUtil.copyProperties(setmeal, setmealDto);
        // 3.2、将setmealDishList 设置到 setmealDto中
        setmealDto.setSetmealDishes(list);
        //4、返回 setmealDto
        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R updateSetmeal(@RequestBody SetmealDto setmealDto ) {
        //1、根据id更新 setmeal 套餐表数据 update setmeal set xx=?,.. where id =?
        //根据id更新 setmeal 套餐表数据
        setmealService.updateById(setmealDto);
        //2、操作套餐对应的菜品数据： setmeal_dish
        //2.1 先根据套餐id删除套餐对应的菜品数据： delete from setmeal_dish where setmeal_id =?
        // 获取套餐id   setmealDto.getId()
//        Long id = setmealDto.getId();
        //先根据套餐id删除套餐对应的菜品数据：
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(qw);
        // 使用 setmealDishMapper 根据套餐id进行删除 ：delete from setmeal_dish where setmeal_id =?
        // 重新添加新的套餐对应的菜品数据
        //先获取所有菜品
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        List<SetmealDish> collect = setmealDishes.stream().map(setmealDish -> {
                    setmealDish.setSetmealId(setmealDto.getId());
                    return setmealDish;
                }
        ).collect(Collectors.toList());
        setmealDishService.saveBatch(collect);
        return R.success("修改成功");
        /*
        //2.2 重新添加新的套餐对应的菜品数据 insert setmeal_dish values (..)
        // setmealDto.getSetmealDishes() 获取套餐的菜品集合 List<SetmealDish>
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        // 遍历套餐菜品集合数据
        for (SetmealDish setmealDish : setmealDishes) {
            // 有没有数据需要set ： 设置套餐id  setSetmealId
            setmealDish.setSetmealId(id);
            // 添加套餐菜品数据 insert
            setmealDishService.saveBatch(setmealDishes);*/
    }

    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#categoryId+'_'+#status")
    public R<List<Setmeal>> listByCategoryId(Long categoryId ,Integer status){
        //select * from setmeal where category_id =? and status =?
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.eq(Setmeal::getCategoryId,categoryId);
        qw.eq(Setmeal::getStatus,status);
        List<Setmeal> list = setmealService.list(qw);
        return  R.success(list);
    }
}
